package org.han.login.service.impl;

import org.han.login.constant.LoginConstant;
import org.han.login.service.ILoginService;
import org.han.org.domain.Employee;
import org.han.org.dto.LoginDTO;
import org.han.org.mapper.EmployeeMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

@Service
public class LoginServiceImpl implements ILoginService {
    @Resource
    private EmployeeMapper mapper;

    @Override
    public Map<String, Object> login(LoginDTO dto) {
        // 判断账号密码是否为空
        if(StringUtils.isEmpty(dto.getUsername()) || StringUtils.isEmpty(dto.getPassword())){
            throw new RuntimeException("用户名或密码不能为空!");
        }
        // 根据用户名查询员工信息
        Employee employee = mapper.loadByUsername(dto.getUsername());
        if(Objects.isNull(employee)){
            throw new RuntimeException("账号或密码错误!请重新输入~~~");
        }
        // 判断密码是否正确
        if(!dto.getPassword().equals(employee.getPassword())){
            throw new RuntimeException("账号或密码错误!请重新输入~~~");
        }
        // 登陆成功 将信息返回给前端
        HashMap<String, Object> map = new HashMap<>();
        map.put("loginUser",employee);
        String token = UUID.randomUUID().toString();
        // 将token和对应的员工信息存入LoginConstant常量类
        LoginConstant.loginMap.put(token, employee);
        // 将token返回前端，用于后续做登录拦截时判断用户是否登录
        map.put("token", token);
        employee.setPassword(""); // 将密码设置为空不让前端看见
        map.put("loginUser", employee); // 将用户数据返回给前端
        return map;
    }
}
